package com.androidhuman.example.mapsv2example;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.androidhuman.example.mapsv2example.R.drawable;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.internal.ic;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class ListActivity extends FragmentActivity {
	SharedPreferences userPrefs;
	SharedPreferences.Editor userPrefsEditor;

	// ///////////////////////////////////////////////////

	View btn_map; // 지도 모양 버튼 (뉴스피드 화면에서 등장한다)

	View popup_me;
	LinearLayout menu_more; // 액션바 아이콘 클릭하면 추가로 나오는 메뉴 레이아웃
	// ////////////////////////////////////////////////

	private ListView listview;
	private DataAdapter adapter;

	private ArrayList<CData> alist;

	private TextView user;
	private TextView headline;
	private TextView text;
	private TextView place;
	private TextView detailPlace;
	private TextView likenums;
	private TextView time;
	private ImageView img;
	private ImageView photo;

	private LinearLayout click_like;

	static Context MainContext;

	View btn_hot;
	View btn_new;
	View btn_event;

	View loading;

	static Context mContext;

	TextView text_hot;
	TextView text_new;
	TextView text_event;

	// //////////////////////////////////////////////// 뉴스피드의 custom listview 구현

	int checkActionBar = 1; // 메뉴가 추가로 생성된 상태인지 확인 (다시 사용될일 없음)

	int option_near_or_all = 1;
	int option_hot_or_new_or_event = 0;

	boolean isMap = false;

	int[] check = new int[10000];
	int userid = 0;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		userPrefs = getSharedPreferences("USER", MODE_PRIVATE);
		userPrefsEditor = userPrefs.edit();

		Intent intent = getIntent();
		option_near_or_all = intent.getIntExtra("option_near_or_all", 0);
		isMap = intent.getBooleanExtra("isMap", false);

		setContentView(R.layout.activity_list);
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.permitNetwork().build());

		MainContext = this;

		userid = userPrefs.getInt("myid", 0);

		// /////////////////////////////////////////////////// (각종 뷰들)

		btn_map = (View) findViewById(R.id.btn_map);
		menu_more = (LinearLayout) findViewById(R.id.menu_more);
		popup_me = (View) findViewById(R.id.popup_me);

		loading = (View) findViewById(R.id.loading);

		// //////////////////////////////////////////////////////////// (뉴스피드)

		listview = (ListView) findViewById(R.id.list);
		alist = new ArrayList<CData>();
		adapter = new DataAdapter(this, alist);
		listview.setAdapter(adapter);

		if (isMap == true) {
btn_map.setVisibility(View.GONE);
		}
		showContents(UsingServer.getDataFromServer("report",
				option_near_or_all, option_hot_or_new_or_event, false));

		// //////////////////////////////////////////////////////////////////(리스너들)

		popup_me.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent;
				intent = new Intent(getApplicationContext(), MeActivity.class);
				startActivity(intent);

			}
		});

		btn_map.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				loading.setVisibility(LinearLayout.VISIBLE);

				Handler handler = new Handler() {
					@Override
					public void handleMessage(Message msg) {

						loading.setVisibility(LinearLayout.GONE);

					}
				};

				handler.sendEmptyMessageDelayed(0, 2500);

				new Thread(new Runnable() {
					public void run() {

						Intent intent;
						intent = new Intent(getApplicationContext(),
								MapActivity.class);

						intent.putExtra("option_near_or_all",
								option_near_or_all);

						startActivity(intent);

					}
				}).start();

			}
		});

		mContext = getApplicationContext();

		btn_hot = findViewById(R.id.bt_hot);
		btn_new = findViewById(R.id.bt_new);
		btn_event = findViewById(R.id.bt_event);
		text_hot = (TextView) findViewById(R.id.t_hot);
		text_new = (TextView) findViewById(R.id.t_new);
		text_event = (TextView) findViewById(R.id.t_event);

		TabControll(0);

		btn_hot.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				TabControll(0);
			}

		});
		btn_new.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				TabControll(1);
			}

		});

		btn_event.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				TabControll(2);
			}

		});

	}

	// }

	public void AddToAdapter(int id, int mPhoto, String headline, String name,
			String text, String place, String detailPlace, String time,
			int img, String like) {

		adapter.add(new CData(this, id, mPhoto, headline, name, text, place,
				detailPlace, time, img, like));
	}

	public void AddToAdapter2(int id, int mPhoto, String headline, String name,
			String text, String place, String detailPlace, String time,
			Bitmap img, String like) {

		adapter.add(new CData(this, id, mPhoto, headline, name, text, place,
				detailPlace, time, img, like));
	}

	public void UpdateAdapter() {

		adapter.notifyDataSetInvalidated();
	}

	// 상단 액션바 아이템 리스너
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case android.R.id.home:

			this.finish();

			break;

		case R.id.item1:

			// mGoogleMap.setMyLocationEnabled (true);
			// LatLng myLocation = new
			// LatLng(mGoogleMap.getMyLocation().getLatitude(),mGoogleMap.getMyLocation().getLongitude());

			Intent intent;
			intent = new Intent(getApplicationContext(), ReportActivity.class);
			startActivity(intent);
			break;

		case R.id.item2:
			if (checkActionBar == 1) {
				menu_more.setVisibility(View.VISIBLE);
				item.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
				checkActionBar = 0;
			} else {
				menu_more.setVisibility(View.INVISIBLE);
				item.setIcon(android.R.drawable.ic_menu_more);

				checkActionBar = 1;
			}

		case R.id.item3:
			break;

		default:
			return false;
		}

		return true;
	}

	// 텍스트를 비트맵에 그려주는 메소드

	// 뉴스피드 관련 어댑터
	class DataAdapter extends ArrayAdapter<CData> {
		private LayoutInflater mInflater;

		public DataAdapter(Context context, ArrayList<CData> object) {
			super(context, 0, object);

			mInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		}

		public View getView(int position, View v, ViewGroup parent) {
			View view = null;
			if (v == null) {
				view = mInflater.inflate(R.layout.list_custom, null);
			} else {
				view = v;
			}
			final CData data = this.getItem(position);
			if (data != null) {
				user = (TextView) view.findViewById(R.id.tv1);
				text = (TextView) view.findViewById(R.id.tv2);
				headline = (TextView) view.findViewById(R.id.headline);
				place = (TextView) view.findViewById(R.id.tv_location);
				detailPlace = (TextView) view.findViewById(R.id.tv_d_place);
				time = (TextView) view.findViewById(R.id.tv_times);
				likenums = (TextView) view.findViewById(R.id.likenum);

				click_like = (LinearLayout) view.findViewById(R.id.click_like);

				img = (ImageView) view.findViewById(R.id.img);
				photo = (ImageView) view.findViewById(R.id.photo);

				View initialize = view.findViewById(R.id.hide);
				initialize.setVisibility(View.GONE);

				user.setText(data.getUser());
				headline.setText(data.getHeadline());
				text.setText(data.getText());
				place.setText(data.getPlace());
				detailPlace.setText(data.getDetailPlace());
				time.setText(data.getTime());
				likenums.setText(data.getLikenum());

				photo.setImageResource(data.getPhoto());

			
				click_like.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub<<<<<<< .mine


						String str=UsingServer.likeUp(data.getID(), option_hot_or_new_or_event);

						likenums.setText(str);
						data.setLikenum(str);
					}

				});
			}
			return view;
		}
	}

	private class CData {
		private String User = "사용자";
		private String Headline;
		private String Text;
		private String Place;
		private String DetailPlace;
		private String Time;
		private Bitmap Img = null;
		private int Photo = R.drawable.male;
		private int check = 0;
		private String likenum = null;
		private int id = 0;

		public CData(Context context, int id, int mPhoto, String mHeadline,
				String mUser, String mText, String mPlace, String detailPlace,
				String time, int mImg, String mLikenum) {
			this.id = id;
			Photo = mPhoto;
			Headline = mHeadline;
			Text = mText;
			Place = mPlace;
			User = mUser;
			DetailPlace = detailPlace;
			Time = time;
			likenum = mLikenum;

			if (mImg != -100) {
				BitmapDrawable drawable = (BitmapDrawable) getResources()
						.getDrawable(mImg);
				Bitmap bitmap = drawable.getBitmap();
				Img = bitmap;
			}
		}

		public CData(Context context, int id, int mPhoto, String mHeadline,
				String mUser, String mText, String mPlace, String detailPlace,
				String time, Bitmap mImg, String mLikenum) {
			this.id = id;
			Photo = mPhoto;
			Headline = mHeadline;
			Text = mText;
			User = mUser;
			Place = mPlace;
			DetailPlace = detailPlace;
			Time = time;
			Img = mImg;
			likenum = mLikenum;

		}

		public String getHeadline() {
			return Headline;
		}

		public String getUser() {
			return User;
		}

		public String getText() {
			return Text;
		}

		public String getPlace() {
			return Place;
		}

		public String getDetailPlace() {
			return DetailPlace;
		}

		public String getTime() {
			return Time;
		}

		public Bitmap getImg() {
			return Img;
		}

		public int getPhoto() {
			return Photo;
		}

		public int getCheck() {

			return check;
		}

		public int getID() {
			return id;
		}

		public String getLikenum() {
			return likenum;
		}

		public void setLikenum(String str) {
			likenum = str;
		}
	}

	// 지도 검색(주소로 위도, 경도값 알아내는) 기능 구현을 위한 메소드

	@SuppressLint("NewApi")
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu, menu);
		getActionBar().setLogo(R.drawable.actionbar_icon2);
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setBackgroundDrawable(
				new ColorDrawable(Color.rgb(248, 157, 105)));
if(isMap==true){
	getActionBar().setTitle("추출된 소식");
}else{
		if (option_near_or_all == 0) {
			getActionBar().setTitle(" 주변 소식");
		} else {
			getActionBar().setTitle(" 전체 소식");
		}
}
		return true;
	
	}

	public void TabControll(int position) {
		String strColorOn = "#FF0000";
		String strColorOff = "#000000";
		listview = (ListView) findViewById(R.id.list);
		switch (position) {
		case 0:
			option_hot_or_new_or_event = 0;

			text_hot.setTextColor(Color.parseColor(strColorOn));
			text_new.setTextColor(Color.parseColor(strColorOff));
			text_event.setTextColor(Color.parseColor(strColorOff));
			break;
		case 1:

			option_hot_or_new_or_event = 1;

			text_hot.setTextColor(Color.parseColor(strColorOff));
			text_new.setTextColor(Color.parseColor(strColorOn));
			text_event.setTextColor(Color.parseColor(strColorOff));
			break;
		case 2:

			option_hot_or_new_or_event = 2;

			text_hot.setTextColor(Color.parseColor(strColorOff));
			text_new.setTextColor(Color.parseColor(strColorOff));
			text_event.setTextColor(Color.parseColor(strColorOn));
			break;

		}
		adapter.clear();
		for (int i = 0; i <= 9000; i++) {
			check[i] = 0;
		}
		if (!isMap)
			showContents(UsingServer.getDataFromServer("report",
					option_near_or_all, option_hot_or_new_or_event, false));
		else
			showContents(UsingServer.getDataFromServer("report_map",
					option_near_or_all, option_hot_or_new_or_event, false));

	}

	public void showContents(String[][] event_article) {
		if (event_article == null)
			return;

		int numOfcontents = event_article.length;
		if (option_hot_or_new_or_event != 2) {
			for (int j = 0; j < numOfcontents; j++) {

				int report_id = Integer.parseInt(TextChecker
						.purifyString(event_article[j][0]));

				// Bitmap imgBitmap = null;
				// imgBitmap =
				// getImageFromURL("http://dev.ts.hs.kr/trend/images/" + "1_"
				// + event_article[j][0] + "_.jpg");

				// if (imgBitmap == null) {

				AddToAdapter(report_id, R.drawable.profile5,
						event_article[j][3], event_article[j][11],
						event_article[j][5], event_article[j][9],
						event_article[j][10], event_article[j][4], -100,
						event_article[j][6]);
				// } else {
				//
				// AddToAdapter2(report_id, R.drawable.profile5,
				// event_article[j][3],
				// event_article[j][11], event_article[j][5],
				// event_article[j][9], event_article[j][10],
				// event_article[j][4], imgBitmap,event_article[j][6]);
				// }
			}
		} else {
			for (int j = 0; j < numOfcontents; j++) {

				int report_id = Integer.parseInt(TextChecker
						.purifyString(event_article[j][0]));
				// Bitmap imgBitmap = null;
				// imgBitmap =
				// getImageFromURL("http://dev.ts.hs.kr/trend/images/" + "2_"
				// + event_article[j][0] + "_.jpg");
				//
				// if (imgBitmap == null) {

				AddToAdapter(report_id, R.drawable.profile5,
						event_article[j][3], event_article[j][12],
						event_article[j][5], event_article[j][10],
						event_article[j][11], event_article[j][4], -100,
						event_article[j][6]);
				// } else {
				//
				// AddToAdapter2(report_id, R.drawable.profile5,
				// event_article[j][3],
				// event_article[j][12], event_article[j][5],
				// event_article[j][10], event_article[j][11],
				// event_article[j][4], imgBitmap,event_article[j][6]);
				// }

			}
		}

		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View arg1,
					int position, long arg3) {

				View Touched = (View) adapter.getView(position, arg1, parent)
						.findViewById(R.id.hide);

				if (check[position] == 0) {
					check[position] = 1;
					int id = adapter.getItem(position).getID();
					Toast toast = Toast.makeText(getBaseContext(),
							Integer.toString(id), Toast.LENGTH_SHORT);
					//toast.show();
					Bitmap imgBitmap = null;

					if(option_hot_or_new_or_event==2){
//					imgBitmap = UsingServer.getImageFromURL("http://dev.ts.hs.kr/trend/images/" + "2_"
//							+ Integer.toString(id) + "_.jpg");
						
					Intent intent = new Intent(getApplicationContext(), EventActivity.class);
					intent.putExtra("event_id", adapter.getItem(position).getID());
					startActivityForResult(intent, 1);return;

					}

					else
						imgBitmap = UsingServer
								.getImageFromURL("http://dev.ts.hs.kr/trend/images/"
										+ "1_" + Integer.toString(id) + "_.jpg");

					ImageView img = (ImageView) adapter.getView(position, arg1,
							parent).findViewById(R.id.img);
					if (imgBitmap == null) {
						img.setVisibility(View.GONE);
					} else {
						img.setVisibility(View.VISIBLE);
						img.setImageBitmap(imgBitmap);
					}
					// ImageView photo = (ImageView) adapter.getView(position,
					// arg1, parent).findViewById(R.id.photo);
					img.setImageBitmap(imgBitmap);
					// photo.setImageBitmap(imgBitmap);

					Touched.setVisibility(View.VISIBLE);
				} else {

					Touched.setVisibility(View.GONE);
					check[position] = 0;
				}

			}
		});
		Toast toast2 = Toast
				.makeText(
						this,
						"검사"
								+ String.valueOf(Integer
										.parseInt(event_article[0][0]) == 1),
						Toast.LENGTH_SHORT);
		// toast2.show();
	}

	public void makeComment(String text, int article_event_id,
			int article_or_event) {
		try {
			String response = HttpRequest.get(
					"http://dev.ts.hs.kr/trend/reporters_make_comments.php",
					true, "user_id", userid, "text", text, "article_event_id",
					article_event_id, "article_or_event", article_or_event)
					.body();
			if (response.compareTo("SUCCESS") == 0) {
				Toast.makeText(this, "성공적으로 작성됨.", Toast.LENGTH_SHORT).show();
			} else if (response.compareTo("ERROR!_THIS_IS_DELETED") == 0) {
				Toast.makeText(this, "글이 지워진것 갑습니다.", Toast.LENGTH_SHORT)
						.show();
			}

		} catch (Exception e) {
			Toast.makeText(this, "인터넷 연결 오류입니다.", Toast.LENGTH_SHORT).show();
		}
	}




	

	public void refresh() {
		TabControll(option_hot_or_new_or_event);
	}

	public void showOld() {
		// UsingServer.getDataFromServer();
	}

}
